package org.example.service.fileService;

import jakarta.annotation.Resource;
import org.apache.poi.xwpf.usermodel.*;
import org.example.domain.file.ElementD;
import org.example.domain.file.InterfaceD;
import org.example.domain.file.RequirementD;
import org.example.domain.iim.Projects;
import org.example.mapper.ElementsMapper;
import org.example.mapper.InterfacesMapper;
import org.example.mapper.ProjectsMapper;
import org.example.mapper.RequirementsMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * @description:
 * @Author: whopxx
 * @CreateTime: 2025-01-07
 */
@Service
public class FileServiceImpl implements FileService{

    @Resource
    private InterfacesMapper interfacesMapper;

    @Resource
    private RequirementsMapper requirementsMapper;

    @Resource
    private ProjectsMapper projectsMapper;

    @Resource
    private ElementsMapper elementsMapper;

    @Override
    public String generateInterfaceDocument(Integer pid) {
        try {
            // 获取static目录路径
            File path = new File(ResourceUtils.getURL("classpath:static").getPath());
            if (!path.exists()) {
                // 如果路径不存在，创建目录
                path.mkdirs();
            }
            // 生成文件名
            String fileName = "接口文档Pid-" + pid + ".docx";
            File dest = new File(path, fileName);

            // 确保父目录存在
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }

            // 创建新的Word文档
            try (XWPFDocument document = new XWPFDocument()) {
                // 创建标题段落
                XWPFParagraph titleParagraph = document.createParagraph();
                titleParagraph.setAlignment(ParagraphAlignment.CENTER); // 居中对齐
                XWPFRun titleRun = titleParagraph.createRun();
                titleRun.setText("接口文档");
                titleRun.setBold(true); // 加粗
                titleRun.setFontSize(20); // 设置字体大小
                titleRun.setColor("000000"); // 设置字体颜色（黑色）
                titleRun.addBreak();

                // 添加项目信息
                Projects project = projectsMapper.selectById(pid);
                XWPFParagraph projectParagraph = document.createParagraph();
                XWPFRun projectRun = projectParagraph.createRun();
                projectRun.setText("项目名称: " + project.getName());
                projectRun.addBreak();
                projectRun.setText("项目标识: " + project.getIdentifier());
                projectRun.addBreak();
                projectRun.setText("项目版本: " + project.getVersion());
                projectRun.addBreak();
                projectRun.setText("项目创建时间: " + project.getCreateTime());
                projectRun.addBreak();
                projectRun.addBreak();

                // 获取接口信息
                List<InterfaceD> interfaces = interfacesMapper.selectByPidDoc(pid);
                if (interfaces.isEmpty()) {
                    XWPFParagraph noDataParagraph = document.createParagraph();
                    XWPFRun noDataRun = noDataParagraph.createRun();
                    noDataRun.setText("该项目下没有接口信息。");
                    noDataRun.setColor("FF0000"); // 设置字体颜色（红色）
                } else {
                    // 遍历接口信息
                    for (InterfaceD inter : interfaces) {
                        // 添加接口标题
                        XWPFParagraph interfaceTitleParagraph = document.createParagraph();
                        interfaceTitleParagraph.setAlignment(ParagraphAlignment.LEFT);
                        XWPFRun interfaceTitleRun = interfaceTitleParagraph.createRun();
                        interfaceTitleRun.setText("接口名称: " + inter.getInterfaceName());
                        interfaceTitleRun.setBold(true);
                        interfaceTitleRun.setFontSize(16);
                        interfaceTitleRun.setColor("0000FF"); // 设置字体颜色（蓝色）
                        interfaceTitleRun.addBreak();

                        // 添加接口详细信息
                        addDetail(document, "接口标识", inter.getInterfaceIdentifier());
                        addDetail(document, "接口类型", inter.getInterfaceType());
                        addDetail(document, "所属对象", inter.getObjectName());
                        addDetail(document, "I/O 类型", inter.getIoType());
                        addDetail(document, "接口描述", inter.getInterfaceDescription());
                        addDetail(document, "接口规则", inter.getInterfaceRules());
                        addDetail(document, "创建时间", inter.getInterfaceCreateTime().toString());

                        // 获取接口下的元素信息
                        List<ElementD> elementDs = elementsMapper.selectByInterfaceId(inter.getInterfaceId());
                        if (!elementDs.isEmpty()) {
                            // 添加元素信息标题
                            XWPFParagraph elementTitleParagraph = document.createParagraph();
                            XWPFRun elementTitleRun = elementTitleParagraph.createRun();
                            elementTitleRun.setText("元素信息");
                            elementTitleRun.setBold(true);
                            elementTitleRun.setFontSize(14);
                            elementTitleRun.setColor("008000"); // 设置字体颜色（绿色）
                            elementTitleRun.addBreak();

                            // 遍历元素信息
                            for (ElementD element : elementDs) {
                                // 添加元素名称
                                XWPFParagraph elementNameParagraph = document.createParagraph();
                                XWPFRun elementNameRun = elementNameParagraph.createRun();
                                elementNameRun.setText("元素名称: " + element.getElementName());
                                elementNameRun.setBold(true);
                                elementNameRun.setFontSize(12);
                                elementNameRun.addBreak();

                                // 添加元素详细信息
                                addDetail(document, "元素标识", element.getElementIdentifier());
                                addDetail(document, "单位", element.getElementUnit());
                                addDetail(document, "物理范围", element.getElementPhysicalRange());
                                addDetail(document, "值域范围", element.getElementValueRange());
                                addDetail(document, "异常处理", element.getElementExceptionHandling());
                                addDetail(document, "加密处理", element.getElementEncryptionHandling());
                                addDetail(document, "精度要求", element.getElementPrecisionRequirement());
                                addDetail(document, "数据类型", element.getDataTypeName());
                                addDetail(document, "数据规格", element.getDataSpecificationProperty());
                                addDetail(document, "对应需求", element.getRequirementName() + " (" + element.getRequirementIdentifier() + ")");
                                addDetail(document, "附加信息", element.getElementAdditionalInfo());

                                // 添加分隔线
                                XWPFParagraph separatorParagraph = document.createParagraph();
                                XWPFRun separatorRun = separatorParagraph.createRun();
                                separatorRun.setText("----------------------------------------");
                                separatorRun.addBreak();
                            }
                        }

                        // 添加分页符
                        document.createParagraph().createRun().addBreak(BreakType.PAGE);
                    }
                }

                // 写入文件
                try (FileOutputStream out = new FileOutputStream(dest)) {
                    document.write(out);
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            // 返回文件名
            return dest.getName();

        } catch (Exception e) {
            throw new RuntimeException("生成接口文档时发生错误", e);
        }
    }

    @Override
    public String generateRequirementDocument(Integer pid) {
        try {
            // 获取static目录路径
            File path = new File(ResourceUtils.getURL("classpath:static").getPath());
            if (!path.exists()) {
                // 如果路径不存在，创建目录
                path.mkdirs();
            }
            // 生成文件名
            String fileName = "需求文档Pid-" + pid + ".docx";
            File dest = new File(path, fileName);

            // 确保父目录存在
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }

            // 创建新的Word文档
            try (XWPFDocument document = new XWPFDocument()) {
                // 创建标题段落
                XWPFParagraph titleParagraph = document.createParagraph();
                titleParagraph.setAlignment(ParagraphAlignment.CENTER); // 居中对齐
                XWPFRun titleRun = titleParagraph.createRun();
                titleRun.setText("需求文档");
                titleRun.setBold(true); // 加粗
                titleRun.setFontSize(20); // 设置字体大小
                titleRun.setColor("000000"); // 设置字体颜色（黑色）
                titleRun.addBreak();

                // 添加项目信息
                Projects project = projectsMapper.selectById(pid);
                XWPFParagraph projectParagraph = document.createParagraph();
                XWPFRun projectRun = projectParagraph.createRun();
                projectRun.setText("项目名称: " + project.getName());
                projectRun.addBreak();
                projectRun.setText("项目标识: " + project.getIdentifier());
                projectRun.addBreak();
                projectRun.setText("项目版本: " + project.getVersion());
                projectRun.addBreak();
                projectRun.setText("项目创建时间: " + project.getCreateTime());
                projectRun.addBreak();
                projectRun.addBreak();

                // 获取需求信息
                List<RequirementD> requirements = requirementsMapper.selectByPidD(pid);
                if (requirements.isEmpty()) {
                    XWPFParagraph noDataParagraph = document.createParagraph();
                    XWPFRun noDataRun = noDataParagraph.createRun();
                    noDataRun.setText("该项目下没有需求信息。");
                    noDataRun.setColor("FF0000"); // 设置字体颜色（红色）
                } else {
                    // 遍历需求信息
                    for (RequirementD requirement : requirements) {
                        // 添加需求标题
                        XWPFParagraph requirementTitleParagraph = document.createParagraph();
                        XWPFRun requirementTitleRun = requirementTitleParagraph.createRun();
                        requirementTitleRun.setText("需求名称: " + requirement.getRequirementName());
                        requirementTitleRun.setBold(true);
                        requirementTitleRun.setFontSize(16);
                        requirementTitleRun.setColor("0000FF"); // 设置字体颜色（蓝色）
                        requirementTitleRun.addBreak();

                        // 添加需求详细信息
                        addDetail(document, "需求标识", requirement.getRequirementIdentifier());
                        addDetail(document, "父需求",
                                requirement.getParentRequirementName() != null ?
                                        requirement.getParentRequirementName() + " (" + requirement.getParentRequirementIdentifier() + ")" : "无");
                        addDetail(document, "需求描述", requirement.getRequirementDescription());
                        addDetail(document, "性能描述", requirement.getPerformanceDescription());
                        addDetail(document, "创建时间", requirement.getRequirementCreateTime().toString());
                        // 添加分隔线
                        XWPFParagraph separatorParagraph = document.createParagraph();
                        XWPFRun separatorRun = separatorParagraph.createRun();
                        separatorRun.setText("----------------------------------------");
                        separatorRun.addBreak();

                    }
                }

                // 写入文件
                try (FileOutputStream out = new FileOutputStream(dest)) {
                    document.write(out);
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            // 返回文件名
            return dest.getName();

        } catch (Exception e) {
            throw new RuntimeException("生成需求文档时发生错误", e);
        }
    }

    /**
     * 添加详细信息段落
     */
    private void addDetail(XWPFDocument document, String label, String value) {
        XWPFParagraph paragraph = document.createParagraph();
        XWPFRun run = paragraph.createRun();
        run.setText(label + ": " + (value != null ? value : "无"));
        run.addBreak();
    }

}
